package com.sita.bike.task;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.sita.bike.event.DrawResourceEvent;
import com.sita.bike.rest.model.Resource2;
import com.sita.bike.utils.AccountUtils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by manhongyun on 15/11/12.
 */
public class ResoureListLoadTask extends AsyncTask<Void, Void, Void> {
    private List<Resource2> mResource;

    public ResoureListLoadTask(List<Resource2> resources) {
        this.mResource = resources;
    }

    @Override
    protected Void doInBackground(Void... params) {

        for (int i = 0; i < mResource.size(); i++) {
            final Resource2 res = mResource.get(i);
            if (res.mAccount != null) {
                Bitmap bitmap = AccountUtils.getUserAvatar(res.mAccount.mAvatar);
                if (bitmap == null) {
                    Log.d("ImageLoader", "download resource");
                    bitmap = ImageLoader.getInstance().loadImageSync(res.mAccount.mAvatar);
                    if (bitmap == null) {
                        ImageLoader.getInstance().loadImage(res.mAccount.mAvatar, new SimpleImageLoadingListener() {
                            @Override
                            public void onLoadingComplete(String imageUri, View view,
                                                          Bitmap loadedImage) {
                                super.onLoadingComplete(imageUri, view, loadedImage);

                                //write your code here to use loadedImage
                                AccountUtils.addUserAvatar(res.mAccount.mAvatar, loadedImage);
                                EventBus.getDefault().post(new DrawResourceEvent(res, res.mAccount.mAccountId, loadedImage));
                            }
                        });
                    }else {
                        AccountUtils.addUserAvatar(res.mAccount.mAvatar, bitmap);
                        Log.d("ImageLoader", "after download resource");
                        EventBus.getDefault().post(new DrawResourceEvent(res, res.mAccount.mAccountId, bitmap));
                    }

                }else {
                    EventBus.getDefault().post(new DrawResourceEvent(res, res.mAccount.mAccountId, bitmap));
                }


            }
        }
        return null;
    }

    //
    public void onProgressUpdate(Void... voids) {
    }

}
